﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Net;
using System.Text;

namespace XKPlatform.Common.Helpers
{
    public static class ImageHelper
    {
        /// <summary>
        /// 根据url 下载图片保存到服务并返回相对路径
        /// </summary>
        /// <param name="url"></param>
        /// <param name="dir"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static string DownLoadImage(string url, string nodePath, string fileName = "")
        {

            var path = Path.Combine(HttpContextCore.Env.WebRootPath, nodePath);
            if (!Directory.Exists(path))//判断路径下是否存在该文件
            {
                //根据目录创建指定的文件夹
                Directory.CreateDirectory(path);
            }
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "GET";
            WebResponse response = request.GetResponse();
            string userPackge = Guid.NewGuid().ToString()+".png";
            if (string.IsNullOrEmpty(fileName))
            {
                fileName = Path.Combine(path, userPackge);
            }
            Image.FromStream(response.GetResponseStream()).Save(fileName, ImageFormat.Png);

            string ret = "/"+nodePath.Replace("\\","/") + "/" + userPackge;
            return ret;
        }
    }
}
